package cn.witque.utils;

import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;


public class SFTPUtil {
    private static final String host = "172.20.10.4";
    private static final int port = 22;
    private static final String username = "root";
    private static final String password = "971021";

    private static ChannelSftp sftp;
    private static SFTPUtil instance = null;

    public static SFTPUtil getInstance() {
        if (instance == null) {
            instance=new SFTPUtil();
            sftp=instance.connect(host,port,username,password);
        }
        return instance;
    }

    /**
     *
     * @param host      主机
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return
     */

    public ChannelSftp connect(String host,int port,String username,String password){
        ChannelSftp sftp=null;
        try {
            JSch jSch=new JSch();
            jSch.getSession(username,host,port);
            Session sshSession=jSch.getSession(username,host,port);
            sshSession.setPassword(password);
            Properties sshConfig=new Properties();
            sshConfig.put("StrictHostKeyChecking","no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel=sshSession.openChannel("sftp");
            channel.connect();
            sftp= (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return sftp;
    }

    /**
     *
     * @param directory
     * @param uploadFile
     * @return
     */
    public boolean upload(String directory,String uploadFile){
        try {
            sftp.cd(directory);
            File file=new File(uploadFile);
            FileInputStream fileInputStream=new FileInputStream(file);
            sftp.put(fileInputStream,file.getName());
            fileInputStream.close();


            return true;
        } catch (SftpException e) {
            e.printStackTrace();
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     *
     * @param directory
     * @param deleteFile
     */
    public void delete(String directory,String deleteFile){
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    public void disconnect(){
        try {
            sftp.getSession().disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        sftp.quit();
        sftp.disconnect();
    }
}
